#include "plat_osl.h"
#include "plat_time.h"
#include "FreeRTOS.h"
#include "task.h"


uint64_t time_count_ms()
{
    return xTaskGetTickCount();
}

uint64_t time_count()
{
    return xTaskGetTickCount() / 1000;
}

void time_delay_ms(uint32_t m_sec)
{
    vTaskDelay(m_sec);
}

void time_delay(uint32_t sec)
{
    vTaskDelay(sec * 1000);
}

handle_t countdown_start(uint32_t ms)
{
    TTim *tim = NULL;
    tim = (TTim *)osl_malloc(sizeof(TTim));
    
    if (tim)
        countdown_set((handle_t)tim, ms);
    
    return (handle_t)tim;
}

void countdown_set(handle_t handle, uint32_t new_ms)
{
    TTim *tim = (TTim *)handle;
    
    if (tim)
        tim->end_tick = time_count_ms() + new_ms;
}

uint32_t countdown_left(handle_t handle)
{
    TTim *tim = (TTim *)handle;
    int32_t left = 0;
    
    if (tim)
        left = tim->end_tick - time_count_ms();
    
    return ((left > 0) ? left : 0);
}

uint32_t countdown_is_expired(handle_t handle)
{
    TTim *tim = (TTim *)handle;
    return ((!tim || (tim->end_tick <= time_count_ms())) ? 1 : 0);
}

void countdown_stop(handle_t handle)
{
  if (handle)
    osl_free((void *)handle);
}
